<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '../stores/app'
import { useSettingsStore } from '../stores/settings'
import { 
  Document, 
  Folder, 
  Edit, 
  Search, 
  Download, 
  Upload, 
  Printer, 
  Setting, 
  RefreshRight
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const appStore = useAppStore()
const settingsStore = useSettingsStore()

// 当前活动菜单
const activeMenu = ref('')
// 菜单是否打开
const menuOpen = ref(false)

// 鼠标悬停在菜单项上的处理
const handleMenuMouseEnter = (menu: string) => {
  // 当有菜单打开时，鼠标悬停在其他菜单项上会自动切换
  if (menuOpen.value) {
    activeMenu.value = menu
  }
}

// 切换主题
const toggleTheme = () => {
  appStore.toggleTheme()
}

// 当前主题
const currentTheme = computed(() => appStore.theme)

// 显示子菜单
const showSubmenu = (menu: string) => {
  if (activeMenu.value === menu && !menuOpen.value) {
    // 如果点击的是当前激活的菜单，但菜单未打开，则打开菜单
    menuOpen.value = true
  } else if (activeMenu.value === menu && menuOpen.value) {
    // 如果点击的是当前激活的菜单，且菜单已打开，则关闭菜单
    activeMenu.value = ''
    menuOpen.value = false
  } else {
    // 如果点击的是其他菜单，则激活该菜单并打开
    activeMenu.value = menu
    menuOpen.value = true
  }
}

// 关闭菜单
const closeMenu = () => {
  activeMenu.value = ''
  menuOpen.value = false
}

// 导航到设置页面
const navigateToSettings = () => {
  router.push({ name: 'settings' })
  closeMenu()
}

// 导航到主页
const navigateToHome = () => {
  router.push({ name: 'home' })
  closeMenu()
}

// 创建新笔记本
const createNewNotebook = () => {
  // 这里需要调用创建笔记本的方法，可以通过事件通知父组件
  emit('create-notebook')
  closeMenu()
}

// 创建新笔记
const createNewNote = () => {
  // 这里需要调用创建笔记的方法，可以通过事件通知父组件
  emit('create-note')
  closeMenu()
}

// 导入导出功能
const importData = () => {
  emit('import-data')
  closeMenu()
}

const exportData = () => {
  emit('export-data')
  closeMenu()
}

// 打印当前笔记
const printNote = () => {
  emit('print-note')
  closeMenu()
}

// 搜索笔记
const searchNotes = () => {
  emit('toggle-search')
  closeMenu()
}

// 刷新应用
const refreshApp = () => {
  emit('refresh-app')
  closeMenu()
}

// 关于应用
const showAbout = () => {
  ElMessageBox.alert(
    'Markdown Editor v1.0.0<br>基于Electron和Vue.js的Markdown编辑器<br>©2024 版权所有',
    '关于',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定'
    }
  )
  closeMenu()
}

// 监听ESC键关闭菜单
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Escape' && menuOpen.value) {
    closeMenu()
  }
}

// 监听点击事件
const handleDocumentClick = (e: MouseEvent) => {
  // 如果点击的是菜单外的区域，关闭菜单
  const target = e.target as HTMLElement
  if (menuOpen.value && !target.closest('.menu-items')) {
    closeMenu()
  }
}

// 当窗口失去焦点时关闭菜单
const handleWindowBlur = () => {
  if (menuOpen.value) {
    closeMenu()
  }
}

// 添加事件监听
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
  document.addEventListener('click', handleDocumentClick)
  window.addEventListener('blur', handleWindowBlur)
})

// 移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeyDown)
  document.removeEventListener('click', handleDocumentClick)
  window.removeEventListener('blur', handleWindowBlur)
})

// 定义事件
const emit = defineEmits([
  'create-notebook',
  'create-note',
  'import-data',
  'export-data',
  'print-note',
  'toggle-search',
  'refresh-app'
])
</script>

<template>
  <div class="top-menu-container">
    <!-- 主菜单栏 -->
    <div class="menu-bar">
      <div class="app-icon">
        <img src="../assets/logo.png" alt="Logo" class="logo-icon" />
      </div>
      
      <!-- 菜单项 -->
      <div class="menu-items">
        <div 
          class="menu-item" 
          @click.stop="showSubmenu('file')" 
          @mouseenter="handleMenuMouseEnter('file')"
          :class="{ active: activeMenu === 'file' }"
        >
          文件
          <!-- 文件子菜单 -->
          <div v-if="activeMenu === 'file'" class="submenu">
            <div class="submenu-item" @click.stop="createNewNotebook">
              <el-icon><Folder /></el-icon>
              <div class="submenu-content">
                <span>新建笔记本</span>
                <span class="shortcut">Ctrl+Shift+N</span>
              </div>
            </div>
            <div class="submenu-item" @click.stop="createNewNote">
              <el-icon><Document /></el-icon>
              <div class="submenu-content">
                <span>新建笔记</span>
                <span class="shortcut">Ctrl+N</span>
              </div>
            </div>
            <div class="submenu-divider"></div>
            <div class="submenu-item" @click.stop="importData">
              <el-icon><Upload /></el-icon>
              <div class="submenu-content">
                <span>导入</span>
              </div>
            </div>
            <div class="submenu-item" @click.stop="exportData">
              <el-icon><Download /></el-icon>
              <div class="submenu-content">
                <span>导出</span>
              </div>
            </div>
            <div class="submenu-divider"></div>
            <div class="submenu-item" @click.stop="printNote">
              <el-icon><Printer /></el-icon>
              <div class="submenu-content">
                <span>打印</span>
                <span class="shortcut">Ctrl+P</span>
              </div>
            </div>
          </div>
        </div>
        
        <div 
          class="menu-item" 
          @click.stop="showSubmenu('edit')" 
          @mouseenter="handleMenuMouseEnter('edit')"
          :class="{ active: activeMenu === 'edit' }"
        >
          编辑
          <!-- 编辑子菜单 -->
          <div v-if="activeMenu === 'edit'" class="submenu">
            <div class="submenu-item">
              <el-icon><Edit /></el-icon>
              <div class="submenu-content">
                <span>撤销</span>
                <span class="shortcut">Ctrl+Z</span>
              </div>
            </div>
            <div class="submenu-item">
              <el-icon><Edit /></el-icon>
              <div class="submenu-content">
                <span>重做</span>
                <span class="shortcut">Ctrl+Y</span>
              </div>
            </div>
            <div class="submenu-divider"></div>
            <div class="submenu-item">
              <div class="submenu-content">
                <span>剪切</span>
                <span class="shortcut">Ctrl+X</span>
              </div>
            </div>
            <div class="submenu-item">
              <div class="submenu-content">
                <span>复制</span>
                <span class="shortcut">Ctrl+C</span>
              </div>
            </div>
            <div class="submenu-item">
              <div class="submenu-content">
                <span>粘贴</span>
                <span class="shortcut">Ctrl+V</span>
              </div>
            </div>
          </div>
        </div>
        
        <div 
          class="menu-item" 
          @click.stop="showSubmenu('view')" 
          @mouseenter="handleMenuMouseEnter('view')"
          :class="{ active: activeMenu === 'view' }"
        >
          视图
          <!-- 视图子菜单 -->
          <div v-if="activeMenu === 'view'" class="submenu">
            <div class="submenu-item" @click.stop="toggleTheme">
              <el-icon><Setting /></el-icon>
              <div class="submenu-content">
                <span>{{ currentTheme === 'dark' ? '浅色主题' : '深色主题' }}</span>
              </div>
            </div>
            <div class="submenu-item" @click.stop="searchNotes">
              <el-icon><Search /></el-icon>
              <div class="submenu-content">
                <span>搜索</span>
                <span class="shortcut">Ctrl+F</span>
              </div>
            </div>
            <div class="submenu-item" @click.stop="refreshApp">
              <el-icon><RefreshRight /></el-icon>
              <div class="submenu-content">
                <span>刷新</span>
                <span class="shortcut">F5</span>
              </div>
            </div>
          </div>
        </div>
        
        <div 
          class="menu-item" 
          @click.stop="showSubmenu('help')" 
          @mouseenter="handleMenuMouseEnter('help')"
          :class="{ active: activeMenu === 'help' }"
        >
          帮助
          <!-- 帮助子菜单 -->
          <div v-if="activeMenu === 'help'" class="submenu">
            <div class="submenu-item" @click.stop="navigateToSettings">
              <el-icon><Setting /></el-icon>
              <div class="submenu-content">
                <span>设置</span>
              </div>
            </div>
            <div class="submenu-divider"></div>
            <div class="submenu-item" @click.stop="showAbout">
              <div class="submenu-content">
                <span>关于</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 标题 -->
      <div class="title">Markdown 编辑器</div>
    </div>
    
    <!-- 点击其他区域关闭子菜单 -->
    <div v-if="menuOpen" class="menu-overlay" @click="closeMenu"></div>
  </div>
</template>

<style scoped>
/* 容器样式 */
.top-menu-container {
  position: relative;
  width: 100%;
  z-index: 100;
}

/* 菜单栏样式 */
.menu-bar {
  height: 30px;
  background-color: var(--top-bar-bg-color, #f5f5f5);
  color: var(--text-color, #333);
  display: flex;
  align-items: center;
  padding: 0 10px;
  -webkit-app-region: drag;
  user-select: none;
  border-bottom: 1px solid var(--border-color, #e0e0e0);
  position: relative;
}

/* 应用图标 */
.app-icon {
  display: flex;
  align-items: center;
  margin-right: 10px;
  -webkit-app-region: no-drag;
}

.logo-icon {
  width: 18px;
  height: 18px;
}

/* 菜单项容器 */
.menu-items {
  display: flex;
  height: 100%;
  -webkit-app-region: no-drag;
  z-index: 11; /* 确保菜单项和子菜单高于其他元素 */
}

/* 单个菜单项 */
.menu-item {
  position: relative;
  padding: 0 10px;
  height: 100%;
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 13px;
  z-index: 11; /* 确保菜单项始终可点击 */
}

.menu-item:hover {
  background-color: var(--hover-color, rgba(0, 0, 0, 0.05));
}

.menu-item.active {
  background-color: var(--active-bg-color, rgba(0, 0, 0, 0.1));
}

/* 标题样式 */
.title {
  flex: 1;
  text-align: center;
  font-size: 14px;
  font-weight: 500;
  margin-right: 130px; /* 根据窗口控制按钮大小调整右边距，使标题视觉上居中 */
}

/* 子菜单 */
.submenu {
  position: absolute;
  top: 30px;
  left: 0;
  min-width: 220px;
  background-color: var(--bg-color, #fff);
  border: 1px solid var(--border-color, #e0e0e0);
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10;
  padding: 5px 0;
  pointer-events: auto; /* 确保子菜单可以接收鼠标事件 */
}

.submenu-item {
  padding: 8px 15px;
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 13px;
}

.submenu-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  white-space: nowrap;
}

.submenu-item:hover {
  background-color: var(--hover-color, rgba(0, 0, 0, 0.05));
}

.submenu-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
  flex-shrink: 0;
}

.submenu-divider {
  height: 1px;
  margin: 5px 0;
  background-color: var(--border-color, #e0e0e0);
}

.shortcut {
  margin-left: 15px;
  color: var(--text-muted-color, #888);
  font-size: 12px;
}

/* 菜单覆盖层 - 点击关闭菜单 */
.menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9; /* 覆盖层z-index低于菜单项，但高于页面其他内容 */
}

/* 深色模式 */
.dark-mode .menu-bar {
  background-color: var(--top-bar-bg-color, #1e1e1e);
  border-color: var(--border-color, #333);
}

.dark-mode .submenu {
  background-color: var(--bg-color, #252526);
  border-color: var(--border-color, #333);
}

.dark-mode .submenu-divider {
  background-color: var(--border-color, #333);
}
</style> 